// Listen for bookmark changes
chrome.bookmarks.onCreated.addListener((_, bookmark) => {
  console.log('Bookmark created:', bookmark);
  // Notify popup about the change
  chrome.runtime.sendMessage({ type: 'BOOKMARK_CREATED', payload: bookmark });
});

chrome.bookmarks.onRemoved.addListener((_, removeInfo) => {
  console.log('Bookmark removed:', removeInfo);
  chrome.runtime.sendMessage({ type: 'BOOKMARK_REMOVED', payload: removeInfo });
});

chrome.bookmarks.onChanged.addListener((_, changeInfo) => {
  console.log('Bookmark changed:', changeInfo);
  chrome.runtime.sendMessage({ type: 'BOOKMARK_CHANGED', payload: changeInfo });
});

// Handle messages from popup
chrome.runtime.onMessage.addListener((message, _, sendResponse) => {
  console.log('Received message:', message);
  
  switch (message.type) {
    case 'FETCH_BOOKMARKS':
      chrome.bookmarks.getTree((bookmarkTreeNodes) => {
        sendResponse({ bookmarks: bookmarkTreeNodes });
      });
      return true; // Will respond asynchronously
      
    case 'EXPORT_BOOKMARKS':
      chrome.bookmarks.getTree((bookmarkTreeNodes) => {
        // Convert bookmarks to HTML format
        const html = generateBookmarkHtml(bookmarkTreeNodes);
        sendResponse({ html });
      });
      return true;
  }
});

function generateBookmarkHtml(bookmarkNodes: chrome.bookmarks.BookmarkTreeNode[]): string {
  let html = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<TITLE>Bookmarks</TITLE>
<H1>Bookmarks</H1>
<DL><p>\n`;

  function processNode(node: chrome.bookmarks.BookmarkTreeNode, level: number) {
    const indent = '    '.repeat(level);
    
    if (node.url) {
      html += `${indent}<DT><A HREF="${node.url}" ADD_DATE="${node.dateAdded}">${node.title}</A>\n`;
    } else if (node.title) {
      html += `${indent}<DT><H3 ADD_DATE="${node.dateAdded}">${node.title}</H3>\n`;
      html += `${indent}<DL><p>\n`;
      if (node.children) {
        node.children.forEach(child => processNode(child, level + 1));
      }
      html += `${indent}</DL><p>\n`;
    }
  }

  bookmarkNodes.forEach(node => processNode(node, 1));
  html += '</DL><p>';
  
  return html;
}

chrome.action.onClicked.addListener(() => {
  chrome.tabs.create({
    url: chrome.runtime.getURL('navigation.html')
  });
});
